#!/bin/sh
# shadowsocks integration for firewall3

CONFIG=softethervpn

uci_get_by_type() {
	local index=0
	if [ -n $4 ]; then
		index=$4
	fi
	local ret=$(uci get $CONFIG.@$1[$index].$2 2>/dev/null)
	echo ${ret:=$3}
}

is_true() {
	case $1 in
		1|on|true|yes|enabled) echo 0;;
		*) echo 1;;
	esac
}

load_config() {
	ENABLED=$(uci_get_by_type softether enable)
	return $(is_true $ENABLED)
}

add_rule()
{
	l2tp=$(uci_get_by_type softether l2tp)
	openvpn=$(uci_get_by_type softether openvpn)
	openvpnport=$(cat /usr/share/softethervpn/vpn_server.config |grep OpenVPN_UdpPortList | awk -F " " '{print $3}')
	sstp=$(uci_get_by_type softether sstp)
  if [ "$l2tp" = "1" ];then
    iptables -I zone_wan_input 2 -p udp -m multiport --dport 500,1701,4500 -m comment --comment "Rule for softethervpn" -j ACCEPT
    iptables -I zone_wan_forward -p esp -m comment --comment "Rule for softethervpn" -j zone_lan_dest_ACCEPT
  fi
  if [ "$openvpn" = "1" ];then
    iptables -I zone_wan_input 2 -p udp --dport $openvpnport -m comment --comment "Rule for softethervpn" -j ACCEPT
    iptables -I zone_wan_input 2 -p tcp --dport $openvpnport -m comment --comment "Rule for softethervpn" -j ACCEPT
  fi 
  if [ "$sstp" = "1" ];then
    iptables -I zone_wan_input 2 -p tcp --dport 443 -m comment --comment "Rule for softethervpn" -j ACCEPT
  fi 
}

! load_config && exit 0
iptables -L zone_wan_input|grep -c "Rule for softethervpn" 2>/dev/null && [ $? -eq 0 ] && exit 0;
add_rule
